const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const path = require('path')
const bodyParser = require('body-parser');
const multer = require('multer')
const urlencodeParser = bodyParser.urlencoded({
    extended: true,
    limit: '50mb'
});
const connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: '12345678',
    database: 'internetcafe'
});
connection.connect(function (err) {
    if (err) {
        console.error('连接失败: ' + err.stack);
        return;
    }
    console.log('连接成功 id ' + connection.threadId);
})
router.get("/selectfood", function (req, res) {
    connection.query('select * from food', function (err, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: result,
            })
        }
    })
});
//配置diskStorage来控制文件存储的位置以及文件名字等
var storage = multer.diskStorage({
    //确定图片存储的位置
    destination: function (req, file, cb) {
        cb(null, './uploadImgs')
    },
        filename: function (req, file, cb) {
            cb(null, Date.now() + file.originalname)
        }
});
var upload = multer({ storage: storage });
let url;
router.post('/addfoodimg', upload.single('file'),function (req, res) {
    url = '/uploadImgs/' + req.file.filename
    res.json({
        code: 200,
        data: url
    })
})
router.get('/addfood', function (req, res) {
    let data = req.query
    let tempdata = {
        id: null,
        name: data.name,
        price: data.price,
        img: data.img

    }
    if (tempdata.name == '' || tempdata.price == '') {
        res.jsonp({
            code: 0,
            msg: '你输入信息不能为空。'
        })
        return;
    }
    connection.query('insert into food set ?', tempdata, (err, result) => {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                code: 1,
                result: data
            })
        }
    })

})
router.get("/delfood", function (req, res) {
    let data = req.query
    console.log(data.id)
    connection.query('delete from  food where id=  "' + data.id + '"  ', function (err, result) {
        if (err) {
            console.log(err);
            res.jsonp({
                fail: 1
            })
        } else {
            res.jsonp({
                result: result,
                code: 1,
                msg: '删除成功。'
            })
        }
    })
});
module.exports = router;